package cn.lingyangwl.agile.infra.job.service.impl;

import cn.lingyangwl.agile.infra.job.mapper.JobLogMapper;
import cn.lingyangwl.agile.infra.job.model.entity.JobLog;
import cn.lingyangwl.agile.infra.job.model.rqrs.JobLogPageReq;
import cn.lingyangwl.agile.infra.job.service.IJobLogService;
import cn.lingyangwl.framework.mybatis.plus.utils.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 定时任务调度日志信息 服务层
 * 
 * @author ruoyi
 */
@Service
public class JobLogServiceImpl implements IJobLogService {
    @Resource
    private JobLogMapper jobLogMapper;

    @Override
    public IPage<JobLog> pageJobLog(JobLogPageReq req) {
        LambdaQueryWrapper<JobLog> lqw = getLqw(req);
        return jobLogMapper.selectPage(PageUtil.to(req), lqw);
    }

    /**
     * 获取quartz调度器日志的计划任务
     * 
     * @param rq 调度日志信息
     * @return 调度任务日志集合
     */
    @Override
    public List<JobLog> listJobLog(JobLogPageReq rq) {
        return jobLogMapper.selectList(getLqw(rq));
    }

    private LambdaQueryWrapper<JobLog> getLqw(JobLogPageReq req) {
        LocalDateTime beginTime = req.getBeginLocalDateTime();
        LocalDateTime endTime = req.getEndLocalDateTime();
        return JobLog.lqw()
                .like(StringUtils.isNotEmpty(req.getJobName()), JobLog::getJobName, req.getJobName())
                .eq(StringUtils.isNotEmpty(req.getStatus()), JobLog::getStatus, req.getStatus())
                .eq(Objects.nonNull(req.getJobId()), JobLog::getJobId, req.getJobId())
                .ge(Objects.nonNull(beginTime), JobLog::getCreatedAt, beginTime)
                .le(Objects.nonNull(endTime), JobLog::getCreatedAt, endTime)
                .orderByDesc(JobLog::getCreatedAt);
    }

    /**
     * 通过调度任务日志ID查询调度信息
     * 
     * @param jobLogId 调度任务日志ID
     * @return 调度任务日志对象信息
     */
    @Override
    public JobLog getById(Long jobLogId) {
        return jobLogMapper.selectById(jobLogId);
    }

    /**
     * 新增任务日志
     * 
     * @param jobLog 调度日志信息
     */
    @Override
    public void save(JobLog jobLog) {
        jobLogMapper.insert(jobLog);
    }

    /**
     * 批量删除调度日志信息
     * 
     * @param logIds 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteByIds(Long[] logIds) {
        return jobLogMapper.deleteBatchIds(Arrays.asList(logIds));
    }

    /**
     * 删除任务日志
     * 
     * @param jobId 调度日志ID
     */
    @Override
    public int deleteById(Long jobId) {
        return jobLogMapper.deleteById(jobId);
    }

    /**
     * 清空任务日志
     */
    @Override
    public void cleanJobLog() {
        jobLogMapper.cleanJobLog();
    }
}
